package br.mg.bhe.ftpobre.command;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTPSClient;

import br.mg.bhe.ftpobre.Main;
import br.mg.bhe.ftpobre.fs.RemoteFile;
import br.mg.bhe.ftpobre.fs.RemoteFileLocalizer;
import br.mg.bhe.ftpobre.gui.MainFrame;
import br.mg.bhe.ftpobre.log.FtpLogView;
import br.mg.bhe.ftpobre.util.LogUtil;
import br.mg.bhe.ftpobre.util.RemoteFileUtil;

/**
 * 
 * @author Aureliano
 */
public class DeleteRemoteFileCommand implements ICommand {

	private static final Logger logger = LogUtil.getLogger(DeleteRemoteFileCommand.class);
	
	private FTPSClient ftp;
	private RemoteFileLocalizer localizer;
	private StringBuilder message;
	
	@Override
	public void execute() {
		if (this.canExecute()) {
			this.doAction();
		}
	}

	@Override
	public boolean canExecute() {
		return Main.getConnectionData().isConnected();
	}
	
	private void doAction() {
		String workingDirectory = MainFrame.getInstance().getAbsolutePathFromRemoteFilePath();
		this.ftp = (FTPSClient) Main.getConnectionData().getFtpClient();
		this.localizer = new RemoteFileLocalizer();
		
		try {			
			RemoteFile file = this.getDeleteCandidateFileName();
			String filePath = workingDirectory + "/" + file.getFile().getName();
			this.message = new StringBuilder("Excluindo objeto '" + filePath + "'");
			
			this.delete(workingDirectory, file);
						
			FtpLogView.log(this.message.toString());
			CommandFactory.command(RefreshRemoteFilesViewCommand.class).execute();
		} catch (IOException ex) {
			logger.log(Level.SEVERE, ex.getMessage(), ex);
			FtpLogView.log("Não foi possível excluir objeto do Servidor FTP. Detalhe: " + ex.getMessage());
			throw new RuntimeException(ex);
		}
	}
	
	private void delete(String workingDirectory, RemoteFile remoteFile) throws IOException {
		String filePath = workingDirectory + "/" + remoteFile.getFile().getName();
		
		if (remoteFile.isDirectory()) {
			List<RemoteFile> files = this.localizer.loadFiles(filePath);
			
			for (RemoteFile f : files) {
				this.delete(filePath, f);
			}
			
			this.ftp.removeDirectory(filePath);
		} else {
			this.ftp.deleteFile(filePath);
		}
		
		this.message.append("\n\tObjeto '" + filePath + "' excluído.");
	}

	private RemoteFile getDeleteCandidateFileName() {
		return RemoteFileUtil.getSelectedFile();
	}
}